package cn.pconline.autoclub.service.bbssync;

import org.springframework.beans.factory.annotation.Autowired;

import cn.pconline.autoclub.entity.Club;
import cn.pconline.autoclub.entity.ClubIntegral;
import cn.pconline.autoclub.entity.ClubMember;
import cn.pconline.autoclub.entity.User;
import cn.pconline.autoclub.service.PetrolService;
import cn.pconline.officialclub.entity.OClub;
import cn.pconline.officialclub.service.OClubService;
import cn.pconline.officialclub.service.OMemberService;

import com.alibaba.fastjson.JSONObject;
import java.util.List;

/**
 * @author zhouruxuan
 * @date 2014年12月4日 下午12:19:44
 */
public class SyncCancelUserVipService extends BbsSyncPetrolService {

    @Autowired
    private OMemberService memberService;
    @Autowired
    private PetrolService petrolService;
    @Autowired
    private OClubService oClubService;

    @Override
    protected int addPetroltoMember(ClubMember clubMember, JSONObject msg) {
        log.info("set vip user need not add petrol to member");
        return 0;
    }

    @Override
    protected int addPetroltoClub(Club club, JSONObject msg) {
        ClubIntegral integral = petrolService.getById(PetrolService.ADD_CLUB_PETROL_ITEM_VIP_QUIT);
        String reason = integral.getName() + "(club-" + club.getClubId() + ")";
        petrolService.addToClubWithinLimit(club.getClubId(), integral.getIntegralId(), integral.getPetrol(), reason, false);
        return 0;
    }

    @Override
    protected long getUserId(JSONObject msg) {
        return msg.getLongValue("userId");
    }

    @Override
    public void process(JSONObject msg, ClubMember clubMember) {

        //验证用户
        long userId = getUserId(msg);
        if (userId <= 0L) {
            log.info("not userId-{}", userId);
            return;
        }

        //判断用户是否登录
        User user = userService.authUser(userId);
        if (user == null || user.getUid() == 0L) {
            log.info("not found user-{}", userId);
            return;
        }

        userService.cancelVip(userId);
        if (clubMember != null) {
            Club club = clubService.getClub(clubMember.getClubId());
            if (club != null) {
                clubService.decreaseVipNum(club.getClubId());
            }
        }
        List<OClub> oClubs = oClubService.listClub4Join(userId);
        //更新品牌车友会的认证数量
        if(oClubs != null){
            for (OClub c : oClubs) {
                int vipNum = memberService.countVipMember(c.getoClubId()) - 1;
                oClubService.updateVipNum(c.getoClubId(), vipNum);
            }
        }
    }
}
